#coding:utf-8
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import MylogForm
from models import Mylog
from django.core.paginator import Paginator, InvalidPage, EmptyPage

def mylog(request):
    '''日记主视图'''
    if request.method == 'POST':
        form = MylogForm(request.POST)
        if form.is_valid():
            #name = form.cleaned_data['name']
            name = request.session.get("username","")
            content = form.cleaned_data['content']
            m = Mylog(name=name, content=content)
            pid = m.id
            m.save()
            return HttpResponseRedirect('/mylog')
    else:
        form = MylogForm()

    mylogs = Mylog.objects.all()
    paginator = Paginator(mylogs, 10)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        contacts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        contacts = paginator.page(paginator.num_pages)

    return render_to_response('logs/mylog.html',                            
                              {'form':form,                              
                               'contacts':contacts}
                              )
